/**
 * 
*/

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>

#include <unistd.h>


void signal_handler(int signum)
{
    printf("(%lx) signum = %d\n", pthread_self(), signum);
    if (signum == SIGALRM)
    {
        alarm(3);
    }
}

void *pthread_fn(void *args)
{

    signal(SIGALRM, signal_handler);

    alarm(3);

    int i = 0;
    for (; i < 100; ++i)
    {
        sleep(3);
        printf("pthread %lx running!\n", pthread_self());
    }

    return NULL;
}

void *pthread_fn2(void *args)
{
    pthread_t th1 = *((pthread_t *)args);
    int i = 0;
    for (; i <= 15; ++i)
    {
        if (10 == i)
        {
            pthread_cancel(th1);
            alarm(0);
        }
        printf("(%lx) i: %d\n", pthread_self(), i);
        sleep(1);
    }

    return NULL;
}

int main(int argc, char const *argv[])
{

    pthread_t pid, pid2;
    pthread_attr_t detach_attr;
    pthread_attr_init(&detach_attr);
    pthread_attr_setdetachstate(&detach_attr, PTHREAD_CREATE_DETACHED);
    if (pthread_create(&pid, &detach_attr, pthread_fn, NULL) != 0)
    {
        perror("pthread_create error: ");
        exit(EXIT_FAILURE);
    }

    if (pthread_create(&pid2, &detach_attr, pthread_fn2, &pid) != 0)
    {
        perror("pthread_create error: ");
        exit(EXIT_FAILURE);
    }

    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGALRM);
    pthread_sigmask(SIG_SETMASK, &set, NULL);

    for (;;)
    {

        printf("main pthread (%lx) running\n", pthread_self());
        sleep(10);
    }
    return 0;
}